package com.sinopec.basemodule.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.sinopec.basemodule.AppConstants;
import com.sinopec.basemodule.R;
import com.sinopec.basemodule.model.ImageBean;
import com.sinopec.basemodule.utils.StringUtils;
import com.sinopec.basemodule.utils.ViewUtils;

import java.io.File;
import java.util.List;

public class PhotoPagerAdapter extends PagerAdapter {

    private List<ImageBean> paths;
    private String waterMark;
    private RequestManager mGlide;
    private int watermarkLayoutRes;

    public PhotoPagerAdapter(RequestManager glide, List<ImageBean> paths, String waterMark, int watermarkLayoutRes) {
        this.paths = paths;
        this.mGlide = glide;
        this.waterMark = waterMark;
        this.watermarkLayoutRes = watermarkLayoutRes;
    }

    @NonNull
    @SuppressLint("CheckResult")
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        final Context context = container.getContext();
        View itemView = LayoutInflater.from(context)
                .inflate(R.layout.picker_picker_item_pager, container, false);

        final FrameLayout watermarkF = itemView.findViewById(R.id.watermark_f);
        ViewUtils.setVisibility(watermarkF, View.GONE);
        if (watermarkLayoutRes >= 0) {
            LayoutInflater.from(context).inflate(watermarkLayoutRes, watermarkF, true);
        }


        final SubsamplingScaleImageView imageView = itemView.findViewById(R.id.iv_pager);

        ImageBean imageBean = paths.get(position);
        int resId = imageBean.getResId();
        if (resId != -1) {
            imageView.setImage(ImageSource.resource(resId));
            container.addView(itemView);
            return itemView;
        }

        String path = imageBean.getNetPath();
        if (path != null && !StringUtils.isUrl(path)) {
            path = AppConstants.IMAGE_SEVER + path;
        }
        final String localPath = paths.get(position).getLocalPath();
        final Uri uri;
        if (!TextUtils.isEmpty(localPath)) {
            uri = Uri.fromFile(new File(localPath));
        } else if (!TextUtils.isEmpty(path)) {
            uri = Uri.parse(path);
        } else {
            uri = null;
        }
        if (null == uri) {
            imageView.setImage(ImageSource.resource(R.drawable.ic_rectangle_picture_no));
        } else {
            RequestOptions requestOptions = new RequestOptions()
                    .dontAnimate()
                    .dontTransform()
                    .skipMemoryCache(true)
                    .placeholder(R.drawable.ic_rectangle_picture_loading)
                    .error(R.drawable.ic_rectangle_picture_error)
                    .fallback(R.drawable.ic_rectangle_picture_error)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
            mGlide
                    .asBitmap()
                    .load(TextUtils.isEmpty(localPath) ? path : localPath)
                    .apply(requestOptions)
                    .into(new CustomViewTarget<SubsamplingScaleImageView, Bitmap>(imageView) {
                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                            imageView.setImage(ImageSource.resource(R.drawable.ic_rectangle_picture_error));
                        }

                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            imageView.setImage(ImageSource.bitmap(resource));
                            if (watermarkLayoutRes >= 0) {
                                ViewUtils.setVisibility(watermarkF, View.VISIBLE);
                            }
                        }

                        @Override
                        protected void onResourceCleared(@Nullable Drawable placeholder) {
                        }
                    });
        }
        /*boolean canLoadImage = AndroidLifecycleUtils.canLoadImage(context);

        if (canLoadImage) {
            final RequestOptions options = new RequestOptions();
            options.dontAnimate()
                    .dontTransform()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .placeholder(R.drawable.picker_ic_photo_black_48dp)
                    .error(R.drawable.picker_ic_broken_image_black_48dp);
            mGlide.setDefaultRequestOptions(options)
                    .asBitmap()
                    .load(uri)
                    .into(new CustomViewTarget<SubsamplingScaleImageView, Bitmap>(imageView) {

                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {

                        }

                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            Bitmap bitmap_new;
                            if (TextUtils.isEmpty(waterMark)) {
                                bitmap_new = resource;
                            } else {
                                bitmap_new = ImageUtils.drawTextsToBitmap(context, resource, waterMark, context.getResources().getDimension(R.dimen.watermark_big_size), context.getResources().getColor(R.color.text_watermark), -30, 60);
                            }
                            imageView.setImage(ImageSource.bitmap(bitmap_new));
                        }

                        @Override
                        protected void onResourceCleared(@Nullable Drawable placeholder) {

                        }
                    });
        }*/

      /*  imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (context instanceof Activity) {
                    if (!((Activity) context).isFinishing()) {
                        ((Activity) context).onBackPressed();
                    }
                }
            }
        });*/

        container.addView(itemView);

        return itemView;
    }


    @Override
    public int getCount() {
        return paths.size();
    }


    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        mGlide.clear((View) object);
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    public String getWaterMark() {
        return waterMark;
    }

    public void setWaterMark(String waterMark) {
        this.waterMark = waterMark;
    }

    public void setWaterMarkLayoutRes(int watermarkLayoutRes) {
        this.watermarkLayoutRes = watermarkLayoutRes;
    }
}
